//
//  NCFilterCollectionView.swift
//  FilterBox
//
//  Created by 张文晏 on 2018/11/9.
//  Copyright © 2018 张文晏. All rights reserved.
//

import UIKit
import SnapKit

public class NCFilterCollectionView: UIView, NCFilterTable {
    public var filterBox: NCFilterBox?
    
    public var filterTabButton: NCFilterTabButton?
    
    public var isMultiSelection: Bool = false
    
    
    typealias sectionItems = [NCFilterBox.IdNameItem]

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet var bottomView: NCFilterBottomView!
    @IBOutlet weak var constraintCollectionViewHeight: NSLayoutConstraint!
    @IBOutlet weak var constraintContentViewTop: NSLayoutConstraint!
    
    func reset() {
        selectedItems = selectedItems.map({ (items) -> [NCFilterBox.IdNameItem] in
            items.map({ (item) -> NCFilterBox.IdNameItem in
                return NCFilterBox.IdNameItem(id: 0, name: "")
            })
        })
        collectionView.reloadData()
    }
    
    func confirm() {
        selectedClosure?(selectedItems)
        hide()
    }
    
    @IBAction func clickBg(_ sender: Any) {
        hide()
    }
    
    private var items = [sectionItems]()
    private var sectionNames = [String]()
    public var selectedItems = [[NCFilterBox.IdNameItem]]()
    public var selectedClosure:((_ items:[[NCFilterBox.IdNameItem]])->())?
    
    public init() {
        super.init(frame: CGRect.init(x: 0, y: 44, width: 375, height: 600))
        _ = fromNib()
        bottomView.resetClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.reset()
        }
        bottomView.confirmClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.confirm()
        }
        let layout = UICollectionViewFlowLayout.init()
        layout.minimumInteritemSpacing = 8
        layout.minimumLineSpacing = 8
        let width = (self.bounds.width - 80)/4
        let height = width * 22/43
        layout.itemSize = CGSize.init(width: width, height: height)
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16)
        layout.headerReferenceSize = CGSize.init(width: self.bounds.width, height: 38)
        layout.footerReferenceSize = CGSize.init(width: self.bounds.width, height: 16)
        collectionView.setCollectionViewLayout(layout, animated: false)
        
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "FilterCollectionViewCell")
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func set(items: [[NCFilterBox.IdNameItem]]){
        self.items = items
        selectedItems = Array<[NCFilterBox.IdNameItem]>.init(repeating: Array<NCFilterBox.IdNameItem>.init(), count: items.count)
    }
    
    public func set(sectionNames: [String]){
        self.sectionNames = sectionNames
    }
    
    public func show(){
        guard let box = filterBox, let owner = box.owner else { return }
        owner.view.insertSubview(self, belowSubview: box.tabButtonContainer)
        self.frame = CGRect.init(x: 0, y: 44, width: owner.view.bounds.width, height: owner.view.bounds.height - 44)
        updateUI()
        
        constraintContentViewTop.constant = -contentView.bounds.height
        layoutIfNeeded()
        constraintContentViewTop.constant = 0
        UIView.animate(withDuration: 0.3) {
            self.layoutIfNeeded()
        }
    }
    
    public func hide(){
        filterTabButton?.isSelected = false
        constraintContentViewTop.constant = -contentView.bounds.height
        UIView.animate(withDuration: 0.3, animations: {
            self.layoutIfNeeded()
        }) { (_) in
            self.removeFromSuperview()
        }
        
    }
    
    func updateUI(){
        collectionView.reloadData()
        setNeedsLayout()
        layoutIfNeeded()
        let height = collectionView.contentSize.height
        constraintCollectionViewHeight.constant = min(height, 500)
    }
    
    func normalLabelStyle(label:UILabel){
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.init(hex:0x333333)
        label.numberOfLines = 2
        label.backgroundColor = UIColor.init(hex:0xF5F5F5)
    }
    
    func hightlightLabelStyle(label: UILabel) {
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.init(hex:0x3480C4)
        label.numberOfLines = 2
        label.backgroundColor = UIColor.init(hex:0xE6F5FF)
    }
    
}

extension NCFilterCollectionView: UICollectionViewDelegate, UICollectionViewDataSource{
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return items.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items[section].count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterCollectionViewCell", for: indexPath)
        cell.contentView.subviews.forEach({$0.removeFromSuperview()})
        let textLabel = UILabel()
        if selectedItems[indexPath.section].contains(where: { (item) -> Bool in
            item.name == items[indexPath.section][indexPath.item].name
        }){
            hightlightLabelStyle(label: textLabel)
        }else{
            normalLabelStyle(label: textLabel)
        }
        cell.contentView.addSubview(textLabel)
        textLabel.snp.makeConstraints { (maker) in
            maker.leading.trailing.top.bottom.equalToSuperview()
        }
        textLabel.textAlignment = .center
        textLabel.text = items[indexPath.section][indexPath.item].name
        return cell
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if !selectedItems[indexPath.section].contains(where: {$0.id == items[indexPath.section][indexPath.item].id}){
            if !self.isMultiSelection {
                selectedItems[indexPath.section].removeAll()
            }
            selectedItems[indexPath.section].append(items[indexPath.section][indexPath.item])
        }else{
            if self.isMultiSelection {
                if let idx = selectedItems[indexPath.section].index(where: {$0.id == items[indexPath.section][indexPath.item].id}){
                    selectedItems[indexPath.section].remove(at: idx)
                }
            }
        }
        collectionView.reloadData()
    }
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader{
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
            view.subviews.forEach({$0.removeFromSuperview()})
            
            let label = UILabel()
            if indexPath.item < sectionNames.count{
                label.text = sectionNames[indexPath.section]
                label.font = UIFont.systemFont(ofSize: 14)
            }
            view.addSubview(label)
            label.snp.makeConstraints { (maker) in
                maker.leading.trailing.equalToSuperview().offset(8)
                maker.height.centerY.equalToSuperview()
            }
            
            return view
        }else if kind == UICollectionView.elementKindSectionFooter{
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footer", for: indexPath)
            view.subviews.forEach({$0.removeFromSuperview()})
            
            let line = UIView.init(frame: CGRect.zero)
            line.backgroundColor = UIColor.init(hex:0xeeeeee)
            view.addSubview(line)
            line.snp.makeConstraints { (maker) in
                maker.leading.equalToSuperview().offset(16)
                maker.centerY.trailing.equalToSuperview()
                maker.height.equalTo(1)
            }
            
            return view
        }
        return UICollectionReusableView.init(frame: .zero)
    }
    
    
}
